<?php
namespace Spider\network;

use lactone\Core\data\SocketData;
use lactone\Core\network\ServerInstance;

class Server extends ServerInstance{

    function run(){

        if(!$this->ip || !$this->port){
            throw new \Exception("请设置监听ip和port的端口!");
        }



        $this->Listening(true);
    }

    /**
     * 对数据进行处理
     * @param $server
     * @param $fd
     * @param $from_id
     * @param $data
     */
    public function onReceive($server,$fd,$from_id,$data){

        \Lactone::debug($this->logMessage($data,'ServerListen'));

        $datas = $this->getData($data);

        foreach($datas as $d){

            \Lactone::debug($this->logMessage($d,'ToTask'));

            $server->task( $d );
        }

    }

    /**
     * 执行任务
     */
    public function onTask($serv,$task_id,$from_id, $data){
        \Lactone::info($this->logMessage("onTask:".$task_id));

        $DataObject = new SocketData($data);
        switch($DataObject->type){
            //执行http任务
            case 'task':
                $task = $DataObject->data;
                $HttpClientWithTask = new HttpClientWithTask([
                    'task' =>$task
                ]);
                $HttpClientWithTask->run();

                break;
            default:
                \Lactone::debug("Spdier task nothing");
                break;
        }
    }

    /**
     * 任务执行完成
     */
    public function onFinish($serv,$task_id, $data){
        \Lactone::debug($this->logMessage("onFinish,task id:".$task_id));
    }

}